from docx import Document
import os
def extract_images(doc_path, output_dir):
    """
    从.docx文件中提取所有图片（包括正文、页眉、页脚）
    参数:
        doc_path: .docx文件路径
        output_dir: 图片输出目录
    """
    os.makedirs(output_dir, exist_ok=True)
    doc = Document(doc_path)
    # 提取文档主体中的图片
    extract_images_from_part(doc.part, output_dir)
    # # 提取页眉页脚中的图片
    # for section in doc.sections:
    #     # 处理页眉
    #     for header in [section.header, section.first_page_header, section.even_page_header]:
    #         if header is not None:
    #             extract_images_from_part(header.part, output_dir, prefix="header_")
    #
    #     # 处理页脚
    #     for footer in [section.footer, section.first_page_footer, section.even_page_footer]:
    #         if footer is not None:
    #             extract_images_from_part(footer.part, output_dir, prefix="footer_")


def extract_images_from_part(part, output_dir, prefix=""):
    """
    从文档部件中提取图片
    参数:
        part: 文档部件对象
        output_dir: 图片输出目录
        prefix: 文件名前缀
    """
    # 获取所有关系
    for rel_id, rel in part.rels.items():
        # 检查是否为图片关系
        if "image" in rel.target_part.content_type:
            image_part = rel.target_part
            image_data = image_part.blob
            # 根据内容类型确定文件扩展名
            content_type = image_part.content_type
            ext = get_extension_from_content_type(content_type)
            # 生成唯一文件名
            filename = f"{prefix}image_{rel_id}.{ext}"
            filepath = os.path.join(output_dir, filename)
            # 保存图片
            with open(filepath, "wb") as f:
                f.write(image_data)
            print(f"保存图片: {filename}")


def get_extension_from_content_type(content_type):
    """根据内容类型返回文件扩展名"""
    mapping = {
        "image/png": "png",
        "image/jpeg": "jpg",
        "image/gif": "gif",
        "image/bmp": "bmp",
        "image/tiff": "tiff",
        "image/x-ms-bmp": "bmp",
        "image/svg+xml": "svg",
        "image/webp": "webp"
    }
    # 返回匹配的扩展名或默认的bin
    return mapping.get(content_type, "bin")

def find_images_in_document(doc_path):
    """
    查找文档中的所有图片位置
    """
    doc = Document(doc_path)
    print("\n查找文档中的图片位置:")
    # 在正文中查找图片
    for i, para in enumerate(doc.paragraphs):
        if has_inline_image(para):
            print(f" - 正文段落 {i + 1} 中包含图片")
    # 在表格中查找图片
    for t, table in enumerate(doc.tables):
        for r, row in enumerate(table.rows):
            for c, cell in enumerate(row.cells):
                for p, para in enumerate(cell.paragraphs):
                    if has_inline_image(para):
                        print(f" - 表格 {t + 1} (行 {r + 1}, 列 {c + 1}) 段落 {p + 1} 中包含图片")
def has_inline_image(paragraph):
    """检查段落是否包含内联图片"""
    if paragraph._element.xpath('.//wp:inline'):
        return True
    return False
def find_icons_in_document(doc_path):
    """
    查找文档中的图标（特殊字体字符）
    """
    doc = Document(doc_path)
    print("\n查找文档中的图标:")
    # 常见图标字体
    icon_fonts = {"Wingdings", "Wingdings 2", "Wingdings 3",
                  "Webdings", "FontAwesome", "Segoe UI Symbol", "Symbol"}
    found = False
    # 检查所有段落
    for i, para in enumerate(doc.paragraphs):
        for run in para.runs:
            if run.font.name:
                font_name = run.font.name
                # 检查是否是图标字体
                if any(icon_font in font_name for icon_font in icon_fonts):
                    print(f" - 段落 {i + 1} 中找到图标字体 '{font_name}': {run.text}")
                    found = True
    if not found:
        print(" - 未找到图标字体")


# 使用示例
if __name__ == "__main__":
    doc_file = "D:\\hbyt\\AI智能投标\\激励及绩效管理_v1.0_2201.docx"
    output_dir = "extracted_images"
    # 提取所有图片
    extract_images(doc_file, output_dir)
    # 查找图片位置
    find_images_in_document(doc_file)
    # 查找图标
    find_icons_in_document(doc_file)